package com.hsylient.demo02;

import lombok.SneakyThrows;
import org.junit.Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class TestDelete {
    private static final String URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    /**
     * statement.execute()的返回值是一个false
     * true if the first result is a ResultSet object; false if it is an update count or there are no results
     * 如果第一个结果是 ResultSet 对象，则为 true；如果是更新计数或没有结果，则为 false
     */
    @Test
    @SneakyThrows
    public void statementDelete() {
        Class.forName(DRIVER);
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        Statement statement = connection.createStatement();
        String sql = "delete from user where id = 4007";
        boolean flag = statement.execute(sql);
        String result = flag ? "删除失败" : "删除成功";
        System.out.println(result);
    }

    /**
     * Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
     * 执行给定的 SQL 语句，它可能是 INSERT、UPDATE 或 DELETE 语句或不返回任何内容的 SQL 语句，例如 SQL DDL 语句。
     * 返回数据库中受影响的行数 0：代表没有数据受到影响 例如删除一个id不在表中的数据
     */
    @Test
    @SneakyThrows
    public void statementExecuteUpdate() {
        Class.forName(DRIVER);
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        Statement statement = connection.createStatement();
        String sql = "delete from user where id = 22";
        int affectCount = statement.executeUpdate(sql);
        System.out.println(affectCount);
    }
}
